package org.example.shoppingmall.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter("/*")
@MultipartConfig
public class CrossOriginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //允许跨域的域名，*号为允许所有。解决跨域访问报错
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        //服务器支持的所有头信息字段
        response.setHeader("Access-Control-Allow-Headers",
                "Origin," +
                        "Access-Control-Request-Headers," +
                        "Access-Control-Allow-Headers," +
                        "DNT," +
                        "X-Requested-With," +
                        "X-Mx-ReqToken," +
                        "Keep-Alive," +
                        "User-Agent," +
                        "X-Requested-With," +
                        "If-Modified-Since," +
                        "Cache-Control," +
                        "Content-Type," +
                        "Accept," +
                        "Connection," +
                        "Cookie," +
                        "X-XSRF-TOKEN," +
                        "X-CSRF-TOKEN," +
                        "Authorization");
        //将Cookie发到服务端，需要指定Access-Control-Allow-Credentials为true;
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //首部字段 Access-Control-Allow-Methods 表明服务器允许客户端使用 POST, GET 和 OPTIONS 方法发起请求
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
        //设置过期时间，这里设置响应最大有效时间为 86400 秒，即24 小时
        response.setHeader("Access-Control-Max-Age", "86400");
        chain.doFilter(request,response);

    }
}
